// 运行代码的钩子
import { useGptMessageStore, usePromptsStore } from '@/stores/index.js'
import { ElMessage } from 'element-plus'
export function useRuncode() {
  const promptStore = usePromptsStore()
  const access_token = '24.fde72a015dcfe071e1965a0eeff89d70.2592000.1715738089.282335-53560975'
  const decoder = new TextDecoder('utf-8')
  const msgStore = useGptMessageStore()
  function parseMultipleDataStrings(inputString) {
    let res = []
    let stack = []
    let i = 0
    let json = ''
    while (i < inputString.length) {
      if (inputString[i] === '{') {
        stack.push('{')
      } else if (inputString[i] === '}') {
        stack.pop()
        // 如果取干净了
        if (stack.length === 0) {
          json += '}'
          res.push(JSON.parse(json))
          json = ''
        }
      }
      if (stack.length !== 0) {
        json += inputString[i]
      }
      i++
    }
    return res
  }
  async function postData(url = '', data = {}) {
    let chunks = ''
    await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    })
      .then((response) => {
        const reader = response.body.getReader()
        return reader.read().then(function process({ done, value }) {
          if (done) {
            console.log('Stream finished')
            promptStore.addAssistantMessage(chunks)
            return
          }
          let text = decoder.decode(value)
          console.log('text ===> ', text)
          try {
            // let json = JSON.parse(removeChars(text))
            // 处理json字符串，利用函数将其转换为对象数组
            let res = parseMultipleDataStrings(text)
            for (let i = 0; i < res.length; i++) {
              chunks += res[i].result
            }
            // chunks += json.result
            msgStore.changeLastOne(chunks)
            console.log('chunks ===> ', chunks)
          } catch (err) {
            console.log(err)
          }
          return reader.read().then(process)
        })
      })
      .catch(console.error)
    // return response.json()
  }

  async function sendStreamData() {
    const url = `https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=${access_token}`
    const data = {
      messages: promptStore.messagesList.messages,
      stream: true
    }
    postData(url, data).then((data) => console.log(data))
  }

  const handleSendMsg = async () => {
    // 1. 将消息加入到消息队列中
    if (msgStore.userMsg.trim() === '') {
      ElMessage({
        type: 'warning',
        message: '不能发送空消息!'
      })
      return (msgStore.userMsg = '')
    }
    let showMsg = msgStore.userMsg
    let newMsg = msgStore.userMsg + 'Python代码的缩进为两个空格。'
    // 将用户的消息添加到展示列表
    msgStore.pushNewMessage(false, showMsg)
    msgStore.userMsg = ''
    promptStore.addUserMessage(newMsg)
    // 添加一个预回答
    msgStore.pushNewMessage(true, '正在思考...')
    sendStreamData()
  }
  return {
    handleSendMsg
  }
}
